﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace DemoMidiDuSkill.Tools
{
    public static class DependancyObjectExtension
    {
        /// <summary>
        /// Search an object by its Name from its parent
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pParent"></param>
        /// <param name="pName"></param>
        /// <returns></returns>
        public static T FindVisualChildByName<T>(this DependencyObject pParent, string pName) where T : DependencyObject
        {
            //Check name
            if (pName == null)
                return null;

            //Search object
            for (int vIndex = 0; vIndex < VisualTreeHelper.GetChildrenCount(pParent); vIndex++)
            {
                DependencyObject vChild = VisualTreeHelper.GetChild(pParent, vIndex);
                string vControlName = vChild.GetValue(Control.NameProperty) as string;

                //Check match on name
                if (vControlName == pName) return vChild as T;
                else
                {
                    //Check current object
                    T vResult = FindVisualChildByName<T>(vChild, pName);
                    if (vResult != null) return vResult;
                }
            }

            //Nothing found
            return null;
        }
    }
}
